import React, { useEffect, useState } from 'react';
import { notification, Statistic, Popover } from 'antd';
import classNames from 'classnames';
import { formatMessage } from 'umi';
import { ClockCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import Button from '@/zero/components/Button';
import styles from './index.less';

const { Countdown } = Statistic;

const Index = (props) => {
  const {
    loadingGlobal = false,

    className,

    value, // 有效期(毫秒)，1000 * 60
    threshold, // 提醒阈值(毫秒)，1000 * 45

    messageText = formatMessage({ id: '详情' }),
    descriptionText = formatMessage({
      id: '是否延长Session有效期',
    }),
    okText = formatMessage({ id: '是' }),
    cancelText = formatMessage({ id: '否' }),

    onOk,

    dispatch, // 排除 dispatch
    ...rest
  } = props;

  const [type, setType] = useState('default'); // default, danger

  const newThreshold = threshold || value * 0.1;

  const newOnOk =
    onOk ||
    (() => {
      console.log('Yes');
      setType('default');
    });

  const closeNotification = () => {
    notification.close('KEY_SESSION_ALERTER');
  };
  const openNotification = () => {
    notification.warning({
      key: 'KEY_SESSION_ALERTER',
      duration: 0,
      style: {
        width: 500,
        marginLeft: 384 - 500,
      },
      message: messageText,
      description: (
        <div style={{ marginTop: 14 }}>
          {descriptionText}
          <Countdown
            value={Date.now() + newThreshold}
            onFinish={() => {
              closeNotification();
            }}
            valueStyle={{
              fontSize: 16,
              lineHeight: '30px',
            }}
          />
          <div style={{ float: 'right', marginTop: 16 }}>
            <Button
              type="danger"
              size="small"
              onClick={() => {
                closeNotification();
              }}
            >
              {cancelText}
            </Button>
            &nbsp;&nbsp;&nbsp;
            <Button
              type="primary"
              size="small"
              onClick={() => {
                closeNotification();
                newOnOk();
              }}
            >
              {okText}
            </Button>
          </div>
        </div>
      ),
    });
  };

  let timer = 0;

  useEffect(() => {
    if (loadingGlobal === true) {
      closeNotification();
      setType('default');
    }

    if (loadingGlobal === false && type === 'default' && value && newThreshold) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        setType('danger');
        openNotification();
      }, value - newThreshold);
    }

    return () => {
      clearTimeout(timer);
    };
  }, [loadingGlobal, type, value, newThreshold]);

  return (
    <Popover
      content={
        value && (
          <>
            <div
              style={{
                display: 'inline-block',
              }}
            >
              <Countdown value={Date.now() + (type === 'danger' ? newThreshold : value)} />
            </div>
            &nbsp;&nbsp;&nbsp;
            {type === 'danger' && (
              <a
                onClick={() => {
                  closeNotification();
                  newOnOk();
                }}
              >
                <ReloadOutlined />
              </a>
            )}
          </>
        )
      }
    >
      <div className={styles.wrapper}>
        <a className={classNames(styles[type], className)} {...rest}>
          <ClockCircleOutlined />
          &nbsp;{formatMessage({ id: 'Session' })}
        </a>
      </div>
    </Popover>
  );
};

Index.displayName = 'SessionAlerter';

export default Index;
